package com.legal.aid.framework.web.service;

import com.legal.aid.common.core.domain.model.AppLoginUser;
import com.legal.aid.common.exception.ServiceException;
import com.legal.aid.common.utils.StringUtils;
import com.legal.aid.common.core.domain.entity.CommonUser;
import com.legal.aid.system.mapper.SysCommonUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


@Service
public class AppUserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SysCommonUserMapper sysCommonUserMapper;

    @Autowired
    private SysPasswordService passwordService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        CommonUser user = sysCommonUserMapper.getCommonUserByUsername(username);
        System.out.println(user);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("用户不存在");
        }
        else if (!user.getIsDeleted().equals("0"))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException("用户已被删除");
        }

        
        passwordService.validateApp(user);

        return createLoginUser(user);
    }

    private UserDetails createLoginUser(CommonUser user)
    {
        return new AppLoginUser(user.getId(),user);
    }
}
